package com.zxx.yuanze.dip;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

import com.zxx.yuanze.ocp.answer.DoubleCache;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * DIP -依赖倒置原则
 *
 * @author zxx on 2020/12/8
 */
public class ImageLoader {

    DoubleCache mCache = new DoubleCache();

    public void displayImage(String url, ImageView imgView) {
        Bitmap bitmap = mCache.get(url);
        if (bitmap == null) {
            downloadImageAsync(url, imgView);
        } else {
            imgView.setImageBitmap(bitmap);
        }
    }

    /**
     * 下载图片 ( 后台下载 )
     *
     * @param url 图片url
     * @param imageView 要显示图片的ImageView
     */
    private void downloadImageAsync(String url, ImageView imageView) {
        Bitmap bmp = downloadBitmap(url);
        mCache.put(url, bmp);
        imageView.setImageBitmap(bmp);
    }

    private Bitmap downloadBitmap(String url) {
        return null/* 从网络中获取图片 */;
    }

    /**
     * 设置缓存策略
     *
     * @param cache 缓存
     */
    public void setImageCache(DoubleCache cache) {
        mCache = cache;
    }

}
